import { ElButton, ElDialog, ElInput } from 'element-plus';
import { createVNode, defineComponent,render,reactive } from 'vue';

const DialogComponent = defineComponent({
  props:{
    option:{
      type: Object
    }
  },
  setup(props,cxt){
    const state = reactive({
      option:props.option,
      isShow:false
    })
    cxt.expose({
      showDialog(option){
        state.isShow = true
        state.option = option
      }
    })
    const cancel = ()=>{
      state.isShow = false
    }

    const confirm = ()=>{
      state.isShow = false
      state.option.onConfirm && state.option.onConfirm(state.option.content)
    }
    return ()=>{
      return <ElDialog v-model={state.isShow} title={state.option.title}>
        {{
          default:()=><ElInput type="textarea" v-model={state.option.content} rows={10}/>,
          footer:()=>state.option.footer && <div>
            <ElButton onClick={ cancel }>取消</ElButton>
            <ElButton type="primary" onClick={confirm}>确定</ElButton>
          </div>
        }}
      </ElDialog>
    }

  }
})

let vm;

export default function $dialog(option) {
  //   手动挂在组件 vue2 通过 new subComponent.$mount() 
  // vue3
  if(!vm){
    let el =  document.createElement('div')
    vm = createVNode(DialogComponent,{option})
    document.body.appendChild((render(vm,el),el))
  }
  // 将组件渲染到el
  let {showDialog} = vm.component.exposed
  showDialog(option)
 

}